﻿using AntDesign;
using IdentityServer4Blazor.Shared;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Threading.Tasks;

namespace IdentityServer4Blazor.Client.ApiRequest
{
    public class RequestBase
    {
        private readonly HttpClient _httpClient;
        private readonly MessageService _messageService;
        //protected string url=string.Empty;
        public RequestBase(HttpClient httpClient, MessageService messageService)
        {
            _httpClient = httpClient;
            _messageService = messageService;
        }
        public async Task<ReponseModel> PostAsJsonAsync<T>(string url,T value)
        {
            var res = await _httpClient.PostAsJsonAsync(url, value);
            return await ReponseHadnler(res);
        }
        public async Task<ReponseModel> GetAsync(string url)
        {
            var res = await _httpClient.GetAsync(url);
            return await ReponseHadnler(res);
        }
        public async Task<ReponseModel> ReponseHadnler(HttpResponseMessage reponse)
        {
            var res = await reponse.Content.ReadAsStringAsync();
            Console.WriteLine(res);
            var model =   JsonSerializer.Deserialize<ReponseModel>(res);
            if (!model.Success)
            {
                await _messageService.Error(model.Msg);
                return model;
            }
            await _messageService.Info("操作成功！");
            return model;
        }
    }
}
